﻿using UnityEngine;
using System.Collections;

public class TilesGenerator : MonoBehaviour {
	public TileSelection TilePrefab;
	public TileSelection[][] Tiles;
	public int width;
	public int height;
	public int NumberOfTiles;
	public int pixPerUnits = 8;		//Ratio of the tiles import
	
	private float _overlap;
	private float tileWidth;
	private float tileHeight;
	private float screenRatio;
	private GameObject[] rows;
	private MatchChecker _checker;
	//private GUIScript _gui;
	
	// Use this for initialization
	void Awake()
	{
		width = 16;		//we'll create a line of inactive tiles all around the active ones
		height = 6;
		//Screen is 480x320
		// 4*16*8pix/u = 512 ~ 480
		tileWidth = 4; //(float)Screen.width/width/pixPerUnits;	//4	and 5 for height
		tileHeight = 5; //(float)Screen.height/(height+2)/pixPerUnits;	//+2 to reserve space for the score, time and buttons
		
		
		NumberOfTiles = width*height;
		// We set a small overlap for the tiles, relative to the screen size as the tiles will be too
		_overlap = 0.1f;

		// On a mobile device we'll use the screen ratio to maximize the tile's size and fill the height
		#if(ON_MOBILE_PLATFORM)
		// We take the overlap into account so as to really wholly fill the screen
		screenRatio = (float)Screen.width/(float)Screen.height;
		#else
		// On a computer we'll scale the camera to fill the width of the screen, the height we always by too big
		screenRatio = 0;
		#endif
		
			
		//Tuiles en quadruple: lambda, 4 vert, 4 violet, 9 bleu
		// Noms: 0_P4, 8_V4, 9_B9, f_bLambda. Les saisons commencent par _ et les fleurs par -
		Sprite[] sprites = Resources.LoadAll<Sprite>("") as Sprite[];
		if( null == sprites )
			return;					// jjj deal with this error

		Tiles = new TileSelection[height+2][];
		for(int i = 0;i<height+2;i++)
			Tiles[i] = new TileSelection[width+2];

		int m = -1, n = 0;		//m is used to parse sprites[], n to know how many of each sprite to use..
		for( int ii = 1; ii < height +1; ii++)
			for( int jj = 1; jj < width+1; jj++)
			{
				if( 0 == n )
				{
					m++;
					n = 6;
				}
				
				Tiles[ii][jj] = Instantiate(TilePrefab) as TileSelection;
				Tiles[ii][jj].Initialize(this,sprites[m].name, sprites[m], screenRatio, _overlap);
				Tiles[ii][jj].renderer.enabled = false;	//Tile invisible for now
				if( 6 == n )
					n = (Tiles[ii][jj].isQuadruple)?3:1;
				else
					n--;
			}
		// Around the game board we create an invisible row (used in the joker algorithm)
		for(int ii = 0; ii < height+2; ii++)
		{
			Tiles[ii][0] = Instantiate(TilePrefab) as TileSelection;
			Tiles[ii][width+1] = Instantiate(TilePrefab) as TileSelection;
		}
		for(int jj = 1; jj < width+1; jj++)
		{
			Tiles[0][jj] = Instantiate(TilePrefab) as TileSelection;
			Tiles[height+1][jj] = Instantiate(TilePrefab) as TileSelection;
		}
		
		// We create the rows
		rows = new GameObject[height+1];
		rows[0] = new GameObject();
		rows[0].name = "GhostRow";
		for (int i = 1; i < height+1; i++)
		{
			rows[i] = new GameObject();
			rows[i].name = "Row"+(i);
		}
		
		
		_checker = this.gameObject.GetComponent<MatchChecker>();
		_checker.Initialize();
	}
	
	public float gameWidth()
	{
		return width*tileWidth*(1-_overlap);
	}


	public void Distribute()
	{
		TileSelection temp;
		
		//We reset the number of tiles
		NumberOfTiles = height*width;
		
		// Shuffle the tiles
		for (int i = 1; i < height+1; i++)
			for(int j = 1; j < width+1; j++)
			{
				temp = Tiles[i][j];
				int swapIndex_i = Random.Range(1,height+1);
				int swapIndex_j = Random.Range(1,width+1);
				Tiles[i][j] = Tiles[swapIndex_i][swapIndex_j];
				Tiles[swapIndex_i][swapIndex_j] = temp;
				
				//We update the tile's position parameters
				Tiles[i][j].i = i;
				Tiles[i][j].j = j;
				Tiles[swapIndex_i][swapIndex_j].i = swapIndex_i;
				Tiles[swapIndex_i][swapIndex_j].j = swapIndex_j;
			}
		
		// Then assign their position on the board
		for (int i = 1; i < height+1; i++)
		{
			// We calculate the future position of the row and make sure it is at 0,0,0 for now
			/* Formula is as follows (exemple for height = 6):
			A) Since the middle of each Tile will be centered on its row, we move all rows 0,5*TileHeight upwards
			so that the line between rows 3 and 4 matches with the middle of the screen => we add 0.5
			B) Half the rows are above the middle, half below, ie. row i=1 will be at position 2.5
			i=2 at 1.5 and i=3 at 0.5 (then the same on the other side) => 0.5 + (height/2 - i)
			C) We wish the tiles to overlap slightly, so instead of having 1*tileHeight between all rows,
			we put a little less => (1 - y_overlap)
			*/

			double fy = (0.5f + (height/2 - i)*(1-_overlap))*tileHeight ;
			rows[i].transform.position = new Vector3(0,0,0);
			Debug.Log("Row["+i+"].pos="+fy+"  _ tileHeight="+tileHeight);
			for(int j = 1; j < width+1; j++)
			{
				float fx = (0.5f + (width/2 - j)*(1-_overlap))*tileWidth;		//default width = 16
				float fz = j/100f;
				Tiles[i][j].Prepare(new Vector3(fx, 0, fz), rows[i].transform);
			}
			// We shift the row and all its tiles to their correct position
			rows[i].transform.position = new Vector3(0,(float)fy,10-i);
		}
		
		// Then we put all the ghost tiles below their Ghostrow parent and deactivate their colliders
		for(int i = 0; i < height+2; i++)
		{
			Tiles[i][0].transform.parent = rows[0].transform;
			Tiles[i][0].collider2D.enabled = false;
			Tiles[i][width+1].transform.parent = rows[0].transform;
			Tiles[i][width+1].collider2D.enabled = false;
		}
		for(int j = 1; j < width+1; j++)
		{
			Tiles[0][j].transform.parent = rows[0].transform;
			Tiles[0][j].collider2D.enabled = false;
			Tiles[height+1][j].transform.parent = rows[0].transform;
			Tiles[height+1][j].collider2D.enabled = false;
		}
		_checker.JokerFinder();
		//_gui.StartGame();
	}
	
	public void HideTiles()
	{
		for( int i = 1; i < height +1; i++ )
			for( int j = 1; j < width +1 ; j++ )
				Tiles[i][j].renderer.enabled = false;
	}
	
	public void ShowTiles()
	{
		for( int i = 1; i < height +1; i++ )
			for( int j = 1; j < width +1 ; j++ )
				if( Tiles[i][j].isVisible )
					Tiles[i][j].renderer.enabled = true;
	}
	
	public void deactivateTilesColliders()
	{
		// We deactivate all colliders, even the ghostrow
		for( int i = 0; i < height +2; i++ )
			for( int j = 0; j < width +2 ; j++ )
				Tiles[i][j].collider2D.enabled = false;	
	}
	
	public void activateTilesColliders()
	{
		for( int i = 1; i < height +1; i++ )
			for( int j = 1; j < width +1 ; j++ )
				if( Tiles[i][j].isVisible )
					Tiles[i][j].collider2D.enabled = true;
	}
}
